<template>
    <div class="changeArea">
        <el-form :model="batchForm" :rules="batchRules" label-width="140px" size="mini" ref="batchForm">
            <el-form-item label="需要修改的字段" prop='modifyField'>
                <el-select v-model="batchForm.modifyField" @change="fieldChange">
                    <el-option v-for="item in modifyFieldOptions" :key="item.value" :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <!-- el-form-item绑定的key在切换生成是否必填的规则时一定要改变，保证表单组件重新渲染 -->
            <el-form-item label="修改为" :prop="findField.value" :key="findField.value">
                <component :is="findField.key" :placeholder="findField.placeholder" :node="findField.node"
                    :name='findField.value' @emitValue='emitValue' ref='component'></component>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import {
        customFieldOther
    } from '@/api/customFieldController'
    import input from './input.vue'
    import inputNumber from './inputNumber.vue'
    import datePicker from './datePicker.vue'
    import tree from './tree.vue'
    import formSelect from './formSelect.vue'
    export default {
        data() {
            return {
                batchForm: {
                    modifyField: 'rate',
                },
                batchRules: {
                    modifyField: [{
                        required: true
                    }]
                },
                fieldProp: '',
                findField: {},
                modifyFieldOptions: [{
                        value: 'rate',
                        label: '报工数配比',
                        key: 'jsk',
                        placeholder: '请输入'
                    },
                    {
                        value: 'planedNumber',
                        label: '计划数',
                        key: 'jsk',
                        placeholder: '请输入'
                    },
                    {
                        value: 'distributionList',
                        label: '分配列表',
                        key: 'tree',
                        placeholder: '请选择'
                    },
                    {
                        value: 'startTime',
                        label: '计划开始时间',
                        key: 'dpi',
                        placeholder: '请选择日期'
                    },
                    {
                        value: 'endTime',
                        label: '计划结束时间',
                        key: 'dpi',
                        placeholder: '请选择日期'
                    }
                ],
                enumFieldType: {
                    ipt: {
                        placeholder: '请填写',
                        key: 'srk'
                    },
                    inputNumber: {
                        placeholder: '请填写',
                        key: 'jsk'
                    },
                    datePicker: {
                        placeholder: '请选择日期',
                        key: 'dpi'
                    },
                    selectChecked: {
                        placeholder: '请选择',
                        key: 'sel',
                    },
                    relevanceObject: {
                        placeholder: '请选择',
                        key: 'sel',
                    },
                    selectRadio: {
                        placeholder: '请选择',
                        key: 'sel',
                    }
                },
            }
        },
        components: {
            // srk: 普通input输入框; jsk: 计数器; dpi: 日期时间选择器; sel: 基础多选/单选;
            srk: input,
            jsk: inputNumber,
            dpi: datePicker,
            tree,
            sel: formSelect
        },
        mounted() {
            this.getCustomFieldOther({
                type: 'processes'
            })
        },
        methods: {
            //需要修改的字段
            getCustomFieldOther(data) {
                customFieldOther(data).then(res => {
                    let tempArr = []
                    //把自定义字段'附件'--'图片'--'关联属性'过滤掉
                    let filterData = res.data.filter(i => {
                        return i.customFieldMess.fieldType != 'upload' &&
                            i.customFieldMess.fieldType != 'picture' &&
                            i.customFieldMess.fieldType != 'relevanceProp'
                    })
                    //将自定义字段得每一项构造成类似checkGroup的每一项结构
                    tempArr = filterData.map((i, index) => {
                        let node = {
                            default: [],
                            isRadio: false,
                            options: []
                        }
                        let checkbox = []
                        if (i.customFieldMess.fieldType == 'selectChecked' || i.customFieldMess
                            .fieldType == 'selectRadio') {
                            checkbox = JSON.parse(i.customFieldMess.checkBox)
                            node.default = i.customFieldMess.fieldType == 'selectChecked' ? [] : ''
                            node.isRadio = i.customFieldMess.fieldType == 'selectChecked'
                            node.options = checkbox.map(k => {
                                return {
                                    label: k.value,
                                    value: k.value
                                }
                            })
                        } else if (i.customFieldMess.fieldType == 'relevanceObject') {
                            node.default = ''
                            node.isRadio = false
                            node.options = i.objectsValue.map(k => {
                                return {
                                    value: k.code + ' - ' + k.name + ' - ' + (k.specification || ''),
                                    label: k.code + ' - ' + k.name + ' - ' + (k.specification || '')
                                }
                            })
                        }
                        return {
                            value: i.customFieldId + '',
                            label: i.customFieldMess.chineseName,
                            key: this.enumFieldType[i.customFieldMess.fieldType].key,
                            placeholder: this.enumFieldType[i.customFieldMess.fieldType].placeholder,
                            type:i.customFieldMess.fieldType,
                            node
                        }
                    })
                    this.modifyFieldOptions = [...this.modifyFieldOptions, ...tempArr]
                    this.fieldChange('rate')
                })
            },
            fieldChange(field) {
                let ruleObj = {}
                this.findField = this.modifyFieldOptions.find(i => i.value == field)
                const {label,key,value} = this.findField
                const numberRule = (rule, v, callback) => {
                    let tempValue = ''
                    let index = String(this.batchForm[value]).indexOf('.')
                    tempValue = index != -1 ? String(this.batchForm[value]).slice(0,index) : String(this.batchForm[value])
                    if (!this.batchForm[value]) {
                        return callback(new Error(`${label}不能为空！`));
                    }else if(tempValue.length > 10){
                        return callback(new Error('整数位最多支持10位数字'));
                    } else if(!(/^[0-9]+(.[0-9]{1,6})?$/.test(this.batchForm[value]))){
                        return callback(new Error('小数点后最多保留6位数字'));
                    }else {
                        callback()
                    }
                }
                if(field == 'rate' || field == 'planedNumber' || key == 'jsk'){
                    ruleObj[field] = [{
                        required: true,
                        validator: numberRule,
                        trigger:'blur'
                    }]
                }else{
                    ruleObj[field] = [{
                        required: true,
                        message:`${label}不能为空！`
                    }]
                }
                this.batchRules = Object.assign(this.batchRules, ruleObj)
                if (field == 'distributionList') {
                    this.$nextTick(() => {
                        this.$refs.component.getDistributionListData()
                    })
                }
            },
            //初始化赋值
            emitValue(payload,idGather){
                const {value} = this.findField
                this.$set(this.batchForm,value,payload)
                if(this.findField.value == 'distributionList'){
                    for (const key in idGather) {
                       this.$set(this.batchForm,key,idGather[key])
                    }
                }
            },
            isValidate() {
                this.$refs.batchForm.validate((valid) => {
                    if (valid) {
                        const modifyForm = {}
                        const copyForm = JSON.parse(JSON.stringify(this.batchForm))
                        const {value} = this.findField
                        Object.keys(copyForm).forEach(k => {
                            if(value != 'distributionList'){
                                if (k != value) delete copyForm[k]
                            }else{
                                if(k != 'depId' && k != 'userId' && k != 'distributions') delete copyForm[k]
                            }
                        })
                        for (const key in copyForm) {
                            if(!isNaN(parseFloat(key)) && isFinite(key)) {
                                let customField = {}
                                customField[key] = this.findField.type == 'selectChecked' ? JSON.stringify(copyForm[key]) : copyForm[key]
                                modifyForm.customField = customField
                            }else{
                                modifyForm[key] = copyForm[key]
                            }
                        }
                        this.$emit('getForm',modifyForm)
                    } else {
                        return false;
                    }
                })
            },
            resetForm() {
                //打开弹框不切换需要修改的字段，触发报工数配比的校验规则，关闭弹框再打开校验未移除，需要手动清除
                if(this.batchForm.modifyField == 'rate') this.$refs.batchForm.clearValidate(['rate'])
                this.batchForm.modifyField = 'rate'
                this.fieldChange('rate')
                this.$refs.component.reset()
            }
        }
    }
</script>